<template>
  <div
    :class="className"
    :style="{height: height, width: width}"
  />
</template>

<script lang="ts">
import * as echarts from 'echarts'
import { EChartsOption } from 'echarts'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ResizeMixin from '@/components/Charts/mixins/resize'
import { ScoreContrastItem } from '@/api-scp/types'

@Component({
  name: 'ScoreContrastChart',
  components: {}
})
export default class extends mixins(ResizeMixin) {
  @Prop({ default: 'chart' }) private className!: string
  @Prop({ default: '100%' }) private width!: string
  @Prop({ default: '200px' }) private height!: string
  @Prop() private title?: string
  @Prop({
    required: true,
    default: []
  }) private scores!: ScoreContrastItem[]

  @Watch('scores', { deep: true })
  private onScoresChange(value: ScoreContrastItem[]) {
    this.setOptions(value)
  }

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  }

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  }

  private async initChart() {
    this.chart = echarts.init(this.$el as HTMLDivElement)

    this.setOptions(this.scores)
  }

  private setOptions(scores: ScoreContrastItem[]) {
    if (!this.chart) {
      return
    }

    const title = { text: this.title ? this.title : undefined }

    const option: EChartsOption =
      {
        title,
        legend: {
          bottom: 0
        },
        grid: {
          left: '45%'
        },
        dataset: {
          dimensions: [
            { name: 'name' },
            { name: 'thisTerm' },
            { name: 'lastTerm' }
          ],
          source: [...scores].reverse()
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category'
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        series: [
          {
            type: 'bar',
            name: '本期得分率'
          },
          {
            type: 'bar',
            name: '上期得分率'
          }
        ]
      }

    console.log(JSON.stringify(option, null, 2))

    this.chart.setOption(option)
  }
}
</script>

<style lang="scss" scoped>

</style>
